package uk.gov.swmprobation.cplitebase;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.oauth.OAuth;
import com.googlecode.flickrjandroid.oauth.OAuthToken;
import com.googlecode.flickrjandroid.people.User;
import com.googlecode.flickrjandroid.photos.GeoData;
import com.googlecode.flickrjandroid.photos.geo.GeoPermissions;
import com.googlecode.flickrjandroid.uploader.UploadMetaData;

public class SendWaiting extends IntentService {

	private static final int MAX_PHOTO_DIMENSION =1024;
	private static final int PHOTO_COMPRESSION = 100;
	private Bitmap myBitmap;
	private byte[] imageBytes;
	
	public SendWaiting() {
		super("SendWaiting");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int localId = intent.getExtras().getInt("localId");
        DatabaseHandler.getInstance(this);
		Project project = DatabaseHandler.getProject(localId);
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		
		String deviceId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
		
		if (PhotoTools.photoExists(project.getImagePath())) {
			HttpClient httpclient = new DefaultHttpClient();
			String httppostString;
			HttpPost httppost;
			if(project.getUpdated()<Project.SENT_GOT_ID){
				httppostString = "http://192.168.10.137:8080/camel2/camel/geo?lat="+project.getLat()+"&lng="+project.getLng()+"&phone="+deviceId;
				Log.e("SendWaiting",httppostString);
				httppost = new HttpPost(httppostString);
				try {
				  HttpResponse response = httpclient.execute(httppost);
				  if (response.getStatusLine().getStatusCode()==200){
					  String responseString = ResponceBody.getResponseBody(response);
						Document responseDoc = XMLfunctions.XMLfromString(responseString);
						NodeList nodes = responseDoc.getElementsByTagName("document");
						int ProjectID = 0;
						for (int i = 0; i < nodes.getLength(); i++) {
							Element e = (Element)nodes.item(i);
							String Trust = XMLfunctions.getValue(e, "trust");
							if(Trust.length()==0){
								project.setProjectStatus("Draft");
								project.save();
								return;
							}
							ProjectID = Integer.parseInt(XMLfunctions.getValue(e, "id"));
							project.setProjectId(ProjectID);
							String ProjectName = XMLfunctions.getValue(e, "address");
							project.setProjectName(ProjectName);
							project.setTrust(Trust);
						}
						project.setUpdated(Project.SENT_GOT_ID);
						project.save();
				  }
				} catch (ClientProtocolException e) {
					//TODO 
					return;
				} catch (IOException e) {
					//TODO
					return;
				}
			}
			
			if(project.getUpdated()<Project.SENT_GOT_FLICKR){
				OAuth oauth = getOAuthToken();
				OAuthToken token = oauth.getToken();
				
				String photoId;
				
				try {
					Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
							token.getOauthToken(), token.getOauthTokenSecret());
	
					UploadMetaData uploadMetaData = new UploadMetaData();
					String project_id_string = project.getTrust()+"-"+String.format("%04d", project.getProjectId());
					uploadMetaData.setTitle(project_id_string);
					ArrayList<String> tags = new ArrayList<String>();
					tags.add(project_id_string);
					uploadMetaData.setTags(tags);
					uploadMetaData.setSafetyLevel("1");
					uploadMetaData.setContentType("1");
					
					myBitmap = PhotoTools.fitBitmapIn(project.getImagePath(), MAX_PHOTO_DIMENSION);
			        ByteArrayOutputStream baos = new ByteArrayOutputStream();
			        myBitmap.compress(Bitmap.CompressFormat.JPEG, PHOTO_COMPRESSION, baos);
			        imageBytes = baos.toByteArray();
					
					photoId = f.getUploader().upload(project.getImagePath(), imageBytes, uploadMetaData);

					GeoData location = new GeoData();
					location.setLatitude((float) project.getLat());
					location.setLongitude((float) project.getLng());
					f.getGeoInterface().setLocation(photoId, location);
					
					f.getPhotosetsInterface().create(project.getProjectName(), project_id_string, photoId)/*.getId()*/;
					project.setImagePath(photoId);
					project.setUpdated(Project.SENT_GOT_FLICKR);
					project.save();
				} catch (Exception e) {
					Log.e("boom!!", "" + e.toString());
					e.printStackTrace();
					return;
				}
			}
			
			if(project.getUpdated()<Project.SENT_FINISHED){
				httppostString = "http://192.168.10.137:8080/camel2/camel/submit?project_id="+project.getProjectId();
				httppostString = httppostString +"&phone="+deviceId;
				httppostString = httppostString +"&photo_id="+project.getImagePath();
				httppostString = httppostString +"&comment="+project.getProjectComment();
				httppostString = httppostString +"&email="+(sharedPref.getString("user_email", ""));
				httppost = new HttpPost(httppostString);
				try {
					  HttpResponse response = httpclient.execute(httppost);
					  String responseString = ResponceBody.getResponseBody(response);
					  String successString = "<result>true</result>";
					  if(responseString.equals(successString)){
					
						  project.setProjectType(Project.TYPE_MINE);
						  project.setProjectStatus("new");
						  project.setUpdated(Project.SENT_FINISHED);
						  project.save();
						  
						  createNotification(project.getProjectId(), project.getProjectName(), project.getTrust());
						  galleryAddPic(project.getImagePath());
						  
							EasyTracker easyTracker = EasyTracker.getInstance(this);
							
							easyTracker.send(MapBuilder
					    		      .createEvent("service_action",     // Event category (required)
					    		                   "project_recieved",  // Event action (required)
					    		                   null,   // Event label
					    		                   null)            // Event value
					    		      .build()
					    		  );
							
							Intent broadcastIntent = new Intent("uk.gov.swmprobation.cpvisibility.event.updatemain");
							sendOrderedBroadcast(broadcastIntent, null);
					  }
					} catch (ClientProtocolException e) {
						//TODO 
						return;
					} catch (IOException e) {
						//TODO
						return;
					}
			}
		} else {
			project.setProjectStatus(Project.TYPE_NAMES[Project.TYPE_DRAFT]);
			project.save();
			Intent broadcastIntent = new Intent("uk.gov.swmprobation.cpvisibility.event.updatemain");
			sendOrderedBroadcast(broadcastIntent, null);
		}
	}
	
	private void createNotification(int projectid,String projectName,String Trust){
		
		String contentText = Helper.shortName(projectName)+" has been submitted to "+Trust+".";;
		String contentTitle = "Project Submitted";
				
		NotificationCompat.Builder mBuilder =
				new NotificationCompat.Builder(this)
				.setAutoCancel(true)
				.setSmallIcon(R.drawable.ic_launcher)	
				.setContentText(contentText)
				.setContentTitle(contentTitle);
				//Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(this, ReviewProjects.class);
				resultIntent.putExtra("project_id", projectid);
				resultIntent.putExtra("updated", true);

				//The stack builder object will contain an artificial back stack for the
				//started Activity.
				//This ensures that navigating backward from the Activity leads out of
				//your application to the Home screen.
				TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
				//Adds the back stack for the Intent (but not the Intent itself)
				stackBuilder.addParentStack(MainActivity.class);
				//Adds the Intent that starts the Activity to the top of the stack
				stackBuilder.addNextIntent(resultIntent);
				PendingIntent resultPendingIntent =
				stackBuilder.getPendingIntent(
				    0,
				    PendingIntent.FLAG_UPDATE_CURRENT
				);
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager mNotificationManager =
				(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				//mId allows you to update the notification later on.
				mNotificationManager.notify(projectid, mBuilder.build());
	}
	
	private void galleryAddPic(String photoPath) {
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    File f = new File(photoPath);
	    Uri contentUri = Uri.fromFile(f);
	    mediaScanIntent.setData(contentUri);
	    this.sendBroadcast(mediaScanIntent);
	}
	
	private static OAuth getOAuthToken() {
		// Restore preferences
		Context context = MyApplication.getContext();
		String oauthTokenString = context.getString(R.string.oauthTokenString);
		String tokenSecret = context.getString(R.string.tokenSecret);
		String userName = context.getString(R.string.userName);
		String userId = context.getString(R.string.userId);

		OAuth oauth = new OAuth();

		if (userId != null) {
			User user = new User();
			user.setUsername(userName);
			user.setId(userId);
			oauth.setUser(user);
		}
		OAuthToken oauthToken = new OAuthToken();
		oauth.setToken(oauthToken);
		oauthToken.setOauthToken(oauthTokenString);
		oauthToken.setOauthTokenSecret(tokenSecret);
		
		return oauth;
	}
	
}
